﻿using System;
using System.Transactions;

namespace TSharp.Core.Repository.EntityFramework
{
    /// <summary>
    /// Entity framework implementation of the transaction.
    /// </summary>
    public class EntityFrameworkTransaction : Disposable, ITransaction
    {
        public EntityFrameworkTransaction(EntityFrameworkUnitOfWork unitOfWork)
        {
            this.UnitOfWork = unitOfWork; 
            //this.TransactionScope = new TransactionScope();
        }

        protected EntityFrameworkUnitOfWork UnitOfWork { get; private set; }

        //protected TransactionScope TransactionScope { get; private set; }

        /// <summary>
        /// Flushes unit of work and commits the transaction scope.
        /// </summary>
        public void Commit()
        {
            this.UnitOfWork.Commit();
            //this.TransactionScope.Complete();
        }

        /// <summary>
        /// Rolls back transaction.
        /// Actually the transaction rollback is handled automatically with Dispose method if
        /// transaction scope was not commited.
        /// </summary>
        public void Rollback()
        {

        }

        private bool disposed;
        protected override void Dispose(bool disposing)
        {
            if (!disposed)
            {
                try
                {
                    if (disposing)
                    {
                        // 释放托管资源
                        UnitOfWork.Dispose();
                        this.UnitOfWork = null;
                    }
                    // 这里释放所有非托管资源
                    disposed = true;
                }
                finally
                {
                    base.Dispose(disposing);
                }
            }
        }

    }
}
